package com.guanghua.brick.html.tag;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.Tag;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.guanghua.brick.html.IContent;
import com.guanghua.brick.html.IControl;
import com.guanghua.brick.html.SQLContent;

public class ContentSQLTag extends BodyTagSupport {
	
	private static Log logger = LogFactory.getLog(ContentSQLTag.class);
	private SQLContent content = new SQLContent();
	public String getId() {return content.getId();}
	public void setId(String id) {
		content.setId(ContentConfigTag.getPagePrefix((HttpServletRequest)pageContext.getRequest(), id));
	}
	public String getSql() {return content.getSql();}
	public void setSql(String sql) {content.setSql(sql);}
	
	
	
	public int doEndTag() throws JspException {
		//获取sql参数
		if (content.getSql() == null)
			content.setSql(this.bodyContent.getString());
		
		//为了避免和jsp中的el表达式冲突，可能查询条件在tag的sql中定义为#{}的方式
		//所以这里做一下替换
		content.setSql(content.getSql().replace("#{", "${"));
		
		//获取content pool，并将content放入
		Map<String, IContent> pool = ContentConfigTag.getContentPool(pageContext.getServletContext());
		pool.put(content.getId(), content);
		logger.trace("content id: " + content.getId());
		logger.trace("content cls: " + content.toString());
		
		//设置父控件中的content属性
		Tag parent = this.getParent();
		if (parent instanceof IControl) {
			((IControl)parent).setContent(content);
		}
		
		return BodyTagSupport.EVAL_PAGE;
	}
	
}
